import datetime
import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from IHome.settings.dev import logger
from apps.houses.models import House
from apps.orders.models import Order


class HouseOrder(View):
    def post(self,request):
        # 1.接受参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 2.校验参数
        if not all([house_id,start_date,end_date]):
            return JsonResponse({'errno':4004,'errmsg':'参数不齐'})
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            assert start_date < end_date, Exception("开始日期大于结束日期")
            # 计算入住天数
            days = (end_date - start_date).days
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "参数错误"})
        # 3.查询指定房屋是否存在
        try:
            house = House.objects.get(pk=house_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno':4004,'errmsg':'没有该房屋数据'})
        # 4.判断当前房屋的房主是否是登录用户
        user = request.user
        if house.user_id == user.id:
            return JsonResponse({'errno': 4105, 'errmsg': '用户身份错误'})
        # 5.查询当前预订时间是否存在冲突
        count = Order.objects.filter(house_id=house_id, begin_date__lt=end_date, end_date__gt=start_date).count()

        if count > 0:
            return JsonResponse({'errno': 4004, 'errmsg': "该房屋已被预订"})
        # 6.生成订单模型，进行下单
        try:
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=days * house.price
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "保存数据失败"})

        # 7.返回下单结果
        return JsonResponse({'errno': 0, 'errmsg': "OK", 'data': {"order_id": order.id}})

    def get(self,request):
        # 获取角色
        role = request.GET.get('role')
        # 校验参数
        if not role:
            return JsonResponse({"errno": 4002, "errmsg": "参数不存在！"})
        if role not in ('custom', 'landlord'):
            return JsonResponse({"errno": 4105, "errmsg": "参数错误！"})
        try:
            # 判断当前角色，获取当前角色的订单信息
            if role == 'custom':
                orders = Order.objects.filter(user=request.user).order_by('-create_time')
            elif role == 'landlord':
                # 获取当前房屋的id
                houses = House.objects.filter(user=request.user)
                houses_id_list = []
                for house in houses:
                    houses_id_list.append(house.id)
                orders = Order.objects.filter(house_id__in=houses_id_list).order_by('-create_time')
        except Exception as e:
            logger.error(e)
            return JsonResponse({"errno": 4001, "errmsg": "查询错误！"})
        order_list = []
        for order in orders:
            order_list.append(
                {
                    "amount": order.amount,
                    "comment": order.comment if order.comment else "",
                    "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "days": order.days,
                    "end_date": order.end_date.strftime("%Y-%m-%d"),
                    "img_url": order.house.index_image_url if order.house.index_image_url else "",
                    "order_id": order.id,
                    "start_date": order.begin_date.strftime("%Y-%m-%d"),
                    "status": order.status,
                    "title": order.house.title
                }
            )
        data = {
            "orders": order_list
        }

        return JsonResponse({'errno': 0, 'errmsg': "OK", 'data': data})

    def put(self, request):
        # 1. 接受参数
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        order_id = json_dict.get('order_id')
        reason = json_dict.get('reason')
        # 2. 校验参数
        if not all([action,order_id]):
            return JsonResponse({'errno': 4004, 'errmsg': '参数不齐'})
        if action not in ("accept","reject"):
            return JsonResponse({'errno': 4004, 'errmsg': '参数不齐'})
        try:
            order = Order.objects.get(pk=order_id,status="WAIT_ACCEPT")
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '订单不存在'})
        user = request.user
        if user != order.house.user:
            return JsonResponse({'errno':4105,'errmsg':'不是该房东'})
        # 3. 修改订单状态
        if action == "accept":
            order.status = "WAIT_COMMENT"
        if action == "reject":
            order.status = "REJECTED"
            if not reason:
                return JsonResponse({'errno':4004, 'errmsg': "请填写拒单原因"})
            order.comment = reason
        # 4. 保存到数据库
        try:
            order.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': "保存数据失败"})
        # 5. 返回
        return JsonResponse({'errno': 0, 'errmsg': 'ok'})


class HouseOrderComment(View):
    def put(self,request):
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        order_id = json_dict.get('order_id')
        # 2.判断参数
        if not all([comment,order_id]):
            return JsonResponse({'errno':4004,'errmsg':'参数不齐'})
        try:
            order = Order.objects.get(pk=order_id,status='WAIT_COMMENT')
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '订单不存在'})
        # 3.修改评论数据
        try:
            order.comment = comment
            order.status = 'COMPLETE'
            order.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': '保存数据失败'})
        # 4.返回数据
        return JsonResponse({'errno': 0, 'errmsg': 'ok'})